#include <iostream>
#include <vector>

using namespace std;

//* 二叉树展开为链表

/**
 * Definition for a binary tree node.
 */
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

/**
 * @brief 114. 二叉树展开为链表
 * https://leetcode.cn/problems/flatten-binary-tree-to-linked-list/
 */
class Solution {
public:
    // 方法一
    // 递归，先展开左右子树，然后把左子树接到右子树上，再把右子树接到左子树的最右节点上
    void flatten(TreeNode* root) {
        if (!root) return;
        auto jointNode = findTheRightestNode(root->left);
        flatten(root->left);
        flatten(root->right);
        if (jointNode) {
            jointNode->right = root->right;
        }
        if (root->left) {
            root->right = root->left;
            root->left = nullptr;
        }
    }

    TreeNode* findTheRightestNode(TreeNode* root) {
        if (!root) return nullptr;
        if (!root->left && !root->right) return root;
        if (!root->right) return findTheRightestNode(root->left);
        return findTheRightestNode(root->right);
    }

    // 方法二
    // 先前序遍历，把节点存到数组里，然后再重新连接
    void flatten_Preorder(TreeNode* root) {
        vector<TreeNode*> order;
        if (!root) return;

        preorder(root, order);
        for (int i=0; i<order.size()-1; i++) {
            order[i]->right = order[i+1];
            order[i]->left = nullptr;
        }

        order[order.size()-1]->right = nullptr;
        order[order.size()-1]->left = nullptr;
    }

    void preorder(TreeNode* root, vector<TreeNode*>& res) {
        if (!root) return;
        res.push_back(root);
        preorder(root->left, res);
        preorder(root->right, res);
    }
};
